package com.com.gmail.at.vssabinin.client;

import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;


import DTO.ScheduleDTO;
import DTO.StationDTO;
import DTO.TicketDTO;

public class SearchTrain extends javax.swing.JDialog {

	private static final long serialVersionUID = 1L;

	public SearchTrain(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        setResizable(false);
        initComponents();
    }
    
    private DefaultComboBoxModel departureComboModel = new DefaultComboBoxModel();
    private DefaultComboBoxModel arrivalComboModel = new DefaultComboBoxModel();
    private SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    private DefaultListModel listTrainModel = new DefaultListModel();
    private List<ScheduleDTO> foundSchedules = null;
    
    private void update() {
    	departureComboModel.removeAllElements();
    	arrivalComboModel.removeAllElements();
    	Main.mainInstance.client.sendThroughProtocol("clientManageStatDat", "");
        Protocol.Message message = Main.mainInstance.client.readThroughProtocol();
        if (message.getType().equals("ok")) {
        	@SuppressWarnings("unchecked")
        	List<StationDTO> station = (List<StationDTO>)message.getObject();
            for (int i = 0; i < station.size(); i++) {
            	departureComboModel.addElement(station.get(i).getStationName());
            	arrivalComboModel.addElement(station.get(i).getStationName());
            }
        } else if (message.getType().equals("no")) {
        	departureComboModel.addElement("No stations in database");
        	arrivalComboModel.addElement("No stations in database");
        }
        SearchTrain.searchTrainInstance.departureStation.setModel(departureComboModel);
        SearchTrain.searchTrainInstance.arrivalStation.setModel(arrivalComboModel);
    }
    
    public static SearchTrain searchTrainInstance = new SearchTrain(Main.mainInstance, true);

    private void initComponents() {

        departureStation = new javax.swing.JComboBox();
        arrivalStation = new javax.swing.JComboBox();
        dateBegin = new javax.swing.JTextField();
        dateEnd = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        trainList = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        searchTrains = new javax.swing.JButton();
        goBack = new javax.swing.JButton();
        buy = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        departureStation.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        arrivalStation.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        dateBegin.setText("2012.11.19 19:11:11");

        dateEnd.setText("2012.11.20 20:11:11");
        
        jScrollPane1.setViewportView(trainList);

        jLabel1.setText("Departure station:");

        jLabel2.setText("Arrival station");

        jLabel3.setText("Date of departure - from this");

        jLabel4.setText("Date of departure to this:");

        searchTrains.setText("search");

        goBack.setText("go back to the main menu");

        buy.setText("buy selected ticket");
        
        buy.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                buyMouseReleased(evt);
           }
        });
        
        goBack.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                goBackMouseReleased(evt);
           }
        });
        
        searchTrains.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
            	searchTrainsMouseReleased(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(departureStation, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addGap(69, 69, 69)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(arrivalStation, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addGap(42, 42, 42)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(dateBegin, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(dateEnd, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(34, 34, 34)
                                .addComponent(searchTrains, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabel4)))
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(goBack)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(buy, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(departureStation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(arrivalStation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(dateBegin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(dateEnd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchTrains))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 301, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(goBack)
                    .addComponent(buy))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }
    public static void main(String args[]) {   
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SearchTrain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SearchTrain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SearchTrain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SearchTrain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
       
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                SearchTrain dialog = new SearchTrain(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    private void goBackMouseReleased(MouseEvent evt) {
    	Main.mainInstance.loginViewSet();
        this.dispose();
    }
    
    private void formWindowOpened(java.awt.event.WindowEvent evt) {
        this.update();
    }
    
    private void searchTrainsMouseReleased(java.awt.event.MouseEvent evt) {
    	this.listTrainModel.clear();
    	Date dateOfBegin = null;
    	Date dateOfEnd = null;
		try {
			dateOfBegin = dataFormat.parse(this.dateBegin.getText());
			dateOfEnd = dataFormat.parse(this.dateEnd.getText());
		} catch (ParseException e) {
			JOptionPane.showMessageDialog(null, "Incorrect date format, try again!"); 
			return;
		} 
		if (dateOfEnd.compareTo(dateOfBegin) > 0) {
			ScheduleDTO schedule = new ScheduleDTO();
	        schedule.setDateOfArrival(dateOfEnd);
	        schedule.setDateOfDeparture(dateOfBegin);
	        schedule.setStation1((String)this.departureStation.getSelectedItem());
	        schedule.setStation2((String)this.arrivalStation.getSelectedItem()); 
	        Main.mainInstance.client.sendThroughProtocol("clientSearchTrains", schedule);
	        Protocol.Message message = Main.mainInstance.client.readThroughProtocol();
	        if (message.getType().equals("ok")) {
	        	@SuppressWarnings("unchecked")
	        	List<ScheduleDTO> schedules = (List<ScheduleDTO>)message.getObject();
	        	this.foundSchedules = schedules;
	            for (int i = 0; i < schedules.size(); i++) {
	            	this.listTrainModel.addElement("Train number:    " + schedules.get(i).getTrainNumber() + "    date of departure:    " + 
	            			dataFormat.format(schedules.get(i).getDateOfDeparture()) + "    date of arrival:    " + dataFormat.format(schedules.get(i).getDateOfArrival()));
	            }
	        } else if (message.getType().equals("no")) {
	        	this.listTrainModel.addElement("No available trains");	
	        }
		}
		this.trainList.setModel(listTrainModel);
    }
    
    private void buyMouseReleased(java.awt.event.MouseEvent evt) {
    	if (foundSchedules != null) {
    		ScheduleDTO selectedSchedule = foundSchedules.get(this.trainList.getSelectedIndex());
    		Main.mainInstance.client.sendThroughProtocol("clientBuyTicket", selectedSchedule);
	        Protocol.Message message = Main.mainInstance.client.readThroughProtocol();
	        if (message.getType().equals("ok")) {
	        	Main.mainInstance.passenger.getTickets().add((TicketDTO) message.getObject());
	        	JOptionPane.showMessageDialog(null, "You have successfully purchased a ticket!"); 
	        } else if (message.getType().equals("no")) {
	        	JOptionPane.showMessageDialog(null, message.getObject().toString()); 
	        }
    	}
    }
    private javax.swing.JButton buy;
    private javax.swing.JButton goBack;
    private javax.swing.JComboBox departureStation;
    private javax.swing.JComboBox arrivalStation;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField dateBegin;
    private javax.swing.JTextField dateEnd;
    private javax.swing.JButton searchTrains;
    private javax.swing.JList trainList;

}
